package com.kaikeba.estack.web.mvc;

import com.kaikeba.estack.common.util.JSONUtil;
import com.kaikeba.estack.web.ApplicationContext;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DispatcherServlet extends javax.servlet.http.HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(DispatcherServlet.class);


    @Override
    public void init(ServletConfig config) throws ServletException {
        String packageNames = ApplicationContext.getApplicationConfigByKey("scanPackageNames", String.class);
        for (String packageName : packageNames.split(",")) {
            try {
                HandlerMapping.load(packageName);
            } catch (IOException e) {
                throw new ServletException(e);
            }
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.    获取用户请求的uri   /xx.do
        String uri = req.getRequestURI();
        String contextPath = req.getContextPath();
        if (!"/".equals(contextPath)) {
            uri = uri.substring(contextPath.length());
        }

        HandlerMapping.MVCMapping mapping = HandlerMapping.get(uri);
        if (mapping == null) {
            resp.sendError(404, "MVC：映射地址不存在：" + uri);
            return;
        }
        Object obj = mapping.getObj();
        Method method = mapping.getMethod();
        Object result = null;

        try {
            //根据当前方法对参数进行解析
            Object[] methodParams = RequestParamResolve.resolve(method);
            if (ArrayUtils.isEmpty(methodParams)) {
                result = method.invoke(obj);
            } else {
                result = method.invoke(obj, methodParams);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        switch (mapping.getResponseType()) {
            case JSON:
                resp.setContentType("text/json;charset=utf-8");
                resp.setCharacterEncoding("utf-8");
                resp.getWriter()
                        .write(JSONUtil.toJSON(result));
                break;
            case VIEW:
                resp.sendRedirect((String) result);
                break;
        }
    }

}
